package cn.com.dbappsecurity.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import cn.com.dbappsecurity.dao.MenuMapper;
import cn.com.dbappsecurity.frame.Constant;
import cn.com.dbappsecurity.frame.datamodal.TreeDataModal.MenuItem;
import cn.com.dbappsecurity.service.IMenu;
import cn.com.dbappsecurity.utils.CookieUtil;

public class MenuImpl extends BaseServiceImpl implements IMenu{

	private MenuMapper menuMapper = getMapper(MenuMapper.class);
	
	/**
	 * 查询所有
	 * @return
	 */
	public List<MenuItem> search(HttpServletRequest req){
		String language = CookieUtil.getValue(req.getCookies(),Constant.LANGUAGE_KEY);
		List<Map<Object,Object>> list = menuMapper.search(language);
		return getChilds(list,0);
	}
	
	/*
	 * 递归组装菜单树(支持无限级)
	 * @param list
	 * @param pid
	 * @return
	 */
	private List<MenuItem> getChilds(List<Map<Object,Object>> list,Integer pid){
		if(list != null){
			List<MenuItem> menus = new ArrayList<MenuItem>();
			for(Map<Object,Object> row : list){
				if(Integer.parseInt(row.get("parentId").toString()) == pid){
					MenuItem item = new MenuItem();
					int id = Integer.parseInt(row.get("id").toString());
					item.setId(id);
					item.setText(row.get("name").toString());
					//attributes
					Map<Object,Object> attr = new HashMap<Object,Object>();
					attr.put("url",row.get("url"));
					attr.put("action",row.get("action"));
					item.setAttributes(attr);
					//childs
					List<MenuItem> childs = getChilds(list,id);
					if(childs != null && childs.size() != 0){
						item.setChildren(childs);
					}
					menus.add(item);
				}
			}
			return menus;
		}
		return null;
	}
	
}
